package org.wangp.gateway.sc.config

import cn.hutool.core.convert.Convert
import org.springframework.context.annotation.Configuration
import org.springframework.security.authorization.AuthorizationDecision
import org.springframework.security.authorization.ReactiveAuthorizationManager
import org.springframework.security.core.Authentication
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.web.server.authorization.AuthorizationContext
import reactor.core.publisher.Mono

/**
 * @author wangpeng (๑•ᴗ•๑)
 * @since 2021/10/6 17:19
 */
@Configuration
class AuthorizationManager : ReactiveAuthorizationManager<AuthorizationContext> {
	override fun check(
		authentication: Mono<Authentication>,
		authorizationContext: AuthorizationContext
	): Mono<AuthorizationDecision> {
		val uri = authorizationContext.exchange.request.uri
		val authorities = listOf<String>()
		return authentication.filter(Authentication::isAuthenticated)
			.flatMapIterable(Authentication::getAuthorities)
			.map(GrantedAuthority::getAuthority)
			.any { authorities.contains(it) }
			.map { AuthorizationDecision(it) }
			.defaultIfEmpty(AuthorizationDecision(false))
	}
}
